<template>
  <div class="leaderboard-page">
    <van-nav-bar
      title="排行榜"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="page-container">
      <van-tabs v-model:active="activeTab" @change="onTabChange">
        <van-tab title="简单">
          <leaderboard-list :level="'easy'" :list="leaderboardData" :loading="loading" />
        </van-tab>
        <van-tab title="中等">
          <leaderboard-list :level="'medium'" :list="leaderboardData" :loading="loading" />
        </van-tab>
        <van-tab title="困难">
          <leaderboard-list :level="'hard'" :list="leaderboardData" :loading="loading" />
        </van-tab>
      </van-tabs>
      
      <div class="user-rank-card" v-if="userRank && userStore.isLoggedIn">
        <div class="rank-title">我的排名</div>
        <div class="rank-content">
          <div class="rank-position">
            <span class="rank-number">{{ userRank.rank }}</span>
            <span class="rank-label">名</span>
          </div>
          <div class="rank-info">
            <div class="username">{{ userStore.username }}</div>
            <div class="time">最佳时间: {{ formatTime(userRank.bestTime) }}</div>
          </div>
        </div>
      </div>
      
      <div class="leaderboard-tips">
        <p>完成游戏并登录账号后，您的成绩将会显示在排行榜上</p>
        <p>排行榜每小时更新一次</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../store/user';
import { getGlobalLeaderboard, getLeaderboardByDifficulty, getUserRank } from '../api/leaderboard';
import { Toast } from 'vant';
import LeaderboardList from '../components/LeaderboardList.vue';

const router = useRouter();
const userStore = useUserStore();

const activeTab = ref(0);
const loading = ref(false);
const leaderboardData = ref([]);
const userRank = ref(null);

const levelMap = ['easy', 'medium', 'hard'];

// 获取排行榜数据
const fetchLeaderboard = async (level) => {
  loading.value = true;
  
  try {
    const res = await getLeaderboardByDifficulty(level, { limit: 50 });
    if (res.code === 0) {
      leaderboardData.value = res.data.rows || [];
    } else {
      Toast('获取排行榜数据失败');
      leaderboardData.value = [];
    }
  } catch (error) {
    console.error('获取排行榜错误', error);
    Toast('获取排行榜数据失败');
    leaderboardData.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取用户排名
const fetchUserRank = async () => {
  if (!userStore.isLoggedIn) {
    userRank.value = null;
    return;
  }
  
  try {
    const res = await getUserRank();
    if (res.code === 0) {
      userRank.value = res.data;
    } else {
      userRank.value = null;
    }
  } catch (error) {
    console.error('获取用户排名错误', error);
    userRank.value = null;
  }
};

// 切换标签页
const onTabChange = (index) => {
  fetchLeaderboard(levelMap[index]);
};

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds) return '--:--';
  
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};

// 返回按钮点击事件
const onClickLeft = () => {
  router.back();
};

onMounted(() => {
  // 获取第一个标签页的排行榜数据
  fetchLeaderboard(levelMap[activeTab.value]);
  
  // 获取用户排名
  fetchUserRank();
});
</script>

<style scoped>
.leaderboard-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.user-rank-card {
  margin: 15px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.12);
}

.rank-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #323233;
}

.rank-content {
  display: flex;
  align-items: center;
}

.rank-position {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20px;
}

.rank-number {
  font-size: 28px;
  font-weight: bold;
  color: #1989fa;
}

.rank-label {
  font-size: 12px;
  color: #969799;
}

.rank-info {
  flex: 1;
}

.username {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.time {
  font-size: 14px;
  color: #969799;
}

.leaderboard-tips {
  margin: 15px;
  padding: 10px;
  background-color: #f2f3f5;
  border-radius: 8px;
  font-size: 12px;
  color: #969799;
  line-height: 1.5;
}
</style>
